<template>
	<view>

		<view class="page">
			<view class="cardView">
				<view class="remarkContent">{{remarkContent}}</view>
				<mpopupHeaderItem label="申请人名称" :value="assignList.operatorName" height="90px">
					<text @click="openSelector">{{assignList.operatorName}} [修改]</text>
				</mpopupHeaderItem>
				<mpopupHeaderRadioItem label="会议时间" height="90px" :custom-class="'custom-align'"
					:custom-style="{ padding: '20rpx' }">
					<view class="example-body">
						<uni-datetime-picker @change="handleDateRangeChange" v-model="dataChange" type="datetimerange"
							@maskClick="maskClick" rangeSeparator="至" />
					</view>
				</mpopupHeaderRadioItem>

				<mpopupHeaderRadioItem label="会议地点" height="90px" :custom-class="'custom-align'"
					:custom-style="{ padding: '20rpx' }">
					<input class="centered-input" v-model="assignList.address" placeholder="请输入会议地点" />
				</mpopupHeaderRadioItem>


				<!-- 其他代码保持不变 -->
				<tableItemGroup :table-data="assignList.workOrderSignatureList" @cell-click="handleTableCellClick"
					:key="tableKey" />

				<!-- 添加更多 -->
				<view class="dashed" @click="showAddMemberDialog">
					<text style="font-size: 20rpx;">+点此添加更多核查组名单</text>
				</view>

			</view>

			<view class="cardView">
				<uni-title type="h2" title="申请人参加首次会议的人员签名" align="center"></uni-title>
				<view class="table-container">
					<uni-table border empty-text="暂无参加记录">

						<uni-tr style="background-color: #e9f1fe">
							<uni-th width="50%" align="center">签名</uni-th>
							<uni-th width="50%" align="center">职务</uni-th>

						</uni-tr>
						<!--表格 -->
					<uni-tr v-for="(item,index) in assignList.workOrderSignatureHuiYiList" :key="index"
					    @click.native="handleHuiYiClick(index)">
					    <uni-td align="center">{{ item.userName }}</uni-td>
					    <uni-td align="center">{{ item.signaturePosition }}</uni-td>
					</uni-tr>
					</uni-table>
				</view>

				<!-- 添加更多 -->
				<view class="dashed" @click="showAddHuiYiDialog">
					<text style="font-size: 20rpx;">+点此添加申请与会人员名单</text>
				</view>

			</view>



			<view class="cardView">
				<uni-title type="h3" title="备注" align="center"></uni-title>

				<view class="full-width-container">
					<textarea @input="handleInput" v-model="this.assignList.remark" class="full-width-textarea"
						placeholder="请编辑评价意见" :maxlength="500"></textarea>
				</view>

			</view>



		</view>
		<view v-if="editStatus!='FALSE'" class="button-container">
			<view class="button-save">
				<button style="flex: 1;" type="primary" @click="submitForm('1')">保存并提交首次会议签到表</button>
			</view>
			<view class="button-save">
				<button style="flex: 1;" type="primary" @click="submitForm('0')">暂存</button>
			</view>
		</view>

		<uni-popup ref="addMemberPopup" type="dialog">
			<view class="member-form-popup">
				<uni-title style="margin-bottom: 20px;" type="h2" :title="isAddingHuiYi ? '设置申请方参会成员' : '新增核查组成员'"
					align="center"></uni-title>

				<uni-forms ref="memberForm" :model="this.assignList.workOrderSignatureList" label-position="top">
					<uni-forms-item label="成员姓名" required name="userName">
						<uni-easyinput v-model="newMember.userName" placeholder="请输入成员姓名" />
					</uni-forms-item>

					<uni-forms-item label-width="150px" label="设置组内职位" required name="signaturePosition">
						<uni-easyinput v-model="newMember.signaturePosition" placeholder="请输入组内职位" />
					</uni-forms-item>

					<uni-forms-item label="签名" required name="signature">
						<signInput :initialImage="newMember.signature" bgColor="#ffffff" :action="uploadUrl"
							@signToUrl="(e) => newMember.signature = JSON.parse(e.data).data"></signInput>
					</uni-forms-item>

					<view class="form-buttons">
						<button class="form-btn cancel" @click="closeMemberPopup">取消</button>
						<button class="form-btn submit" @click="submitMemberForm">提交</button>
					</view>
				</uni-forms>
			</view>
		</uni-popup>

		<!-- 选择器组件 -->
		<enterprise-selector ref="selector" :multiple="true" :initial-selected="selectedList" @confirm="handleConfirm"
			@close="handleClose" />

	</view>
</template>

<script>
	import signInput from "@/components/am-sign-input/am-sign-input.vue"
	import mpopupHeaderItem from "@/components/mpopup-header-item.vue"
	import mpopupHeaderRadioItem from "@/components/mpopup-header-radio-item.vue"
	import mpopupTable from "@/components/mpopup-table.vue"
	import signItem from '@/components/sign-item/sign-item.vue'
	import tableItemGroup from '@/components/table-item/table-item-group.vue'
	import EnterpriseSelector from "@/components/dialog/enterprise-selector.vue"

	import {
		getformat,
		getProject,
		addMedical,
		getMedicalDict,
		addResultList,
		medicalGetInfo,
		medicalUpdate,
		foodProductionAdd,
		foodProductionInfo,
		foodProductionUpdate
	} from '@/api/order'
	import {
		getFoodReport
	} from '@/api/report.js'
	export default {
		components: {
			mpopupHeaderRadioItem,
			mpopupHeaderItem,
			signInput,
			tableItemGroup,
			EnterpriseSelector
		},
		data() {
			return {
				isAddingHuiYi: false, // 新增状态变量
				tableKey: 0,
				// 新增临时成员对象和编辑索引
				newMember: {
					signType: 0,
					userName: '',
					signaturePosition: '',
					signature: ''
				},
				editingIndex: -1, // -1表示新增，其他表示编辑索引
				selectedList: [], // 已选数据
				remarkContent: '',
				editDateType: '',
				tempDate: '',
				assignList: {
					workOrderSignatureList: [{
							showRow: true,
							rowspan: 3,
							group: '核查组',
							signaturePosition: '组长', //签字职位
							userName: '',
							signType: 0,
							signature: ''
						},
						{
							showRow: false,
							rowspan: 1,
							group: '核查组',
							signaturePosition: '成员', //签字职位
							userName: '',
							signType: 0,
							signature: ''
						},
						{
							showRow: false,
							rowspan: 1,
							group: '核查组',
							signaturePosition: '观察员', //签字职位
							userName: '',
							signType: 0,
							signature: ''
						}

					], ////设置核查组成员signType固定=0
					workOrderSignatureHuiYiList: [


					], // //会议人-signType固定=1
					createBy: "", //系统管理员
					auditStatus: "", //暂存给0,提交给1 
					operatorName: "", //公司名称
					checkStartTime: "", //会议开始时间
					checkEndTime: "", //会议结束时间
					address: "", //会议地点
					bidType: "",
					remark: "",
					orderCategory: '',
					workOrderId: '' //工单主键
				},
				editStatus: 'ADD',
				tableData: [],
				dataChange: []

			}
		},
		props: {
			uploadUrl: {
				type: String,
				default: "https://8954wg323mw0.vicp.fun/app/upload/uploadFile"
			},
		},
		onLoad(options) {
			if (options.editStatus != null) {
				const editStatus = decodeURIComponent(options.editStatus);
				const workOrderId = decodeURIComponent(options.workOrderId);

				this.assignList.workOrderId = workOrderId;
				this.editStatus = editStatus;
				this.getfoodProductionInfo(workOrderId);
			} else {
				if (options.orderData) {
					const orderData = JSON.parse(decodeURIComponent(options.orderData));

					const orderid = decodeURIComponent(options.workOrderId);

					this.assignList.operatorName = orderData.operatorName;
					this.assignList.workOrderId = orderid;
					this.assignList.bidType = orderData.bidType;
					this.assignList.orderCategory = orderData.orderCategory;
				}
			}

			this.getMedicalDict('check_staff_form_wenan');

		},
		computed: {

		},
		// 在数据更新时调用统计方法
		watch: {

		},
		methods: {
			// 会议人员点击处理
			handleHuiYiClick(index) {
				this.isAddingHuiYi = true
				this.editingIndex = index
				this.newMember = {
					...this.assignList.workOrderSignatureHuiYiList[index]
				}
				this.$refs.addMemberPopup.open()
			},
			// 添加与会人员
			showAddHuiYiDialog() {
				this.isAddingHuiYi = true
				this.editingIndex = -1
				this.newMember = {
					userName: '',
					signaturePosition: '',
					signature: '',
					signType: 1 // 固定为会议类型
				}
				this.$refs.addMemberPopup.open()
			},
			handleInput(e) {
				// 手动截断字符（解决部分机型兼容性问题）
				this.assignList.remark = e.target.value.slice(0, 500);
			},
			// 打开选择器
			openSelector() {
				this.$refs.selector.open()
			},

			// 确认回调
			handleConfirm(selectedItems) {
				this.selectedList = selectedItems
				this.assignList.operatorName = this.selectedList[0].operatorName
				console.log('已选数据:', selectedItems)
			},

			// 关闭回调
			handleClose() {
				console.log('选择器已关闭')
			},

			// 如果需要主动设置选中数据
			updateSelection() {
				// 可以通过修改 selectedList 来更新初始选中状态
				this.selectedList = [{
					uniqueId: '123',
					operatorName: '示例企业',
					address: '示例地址'
				}]
			},
			handleTableCellClick(index) {
				this.editingIndex = index;
				this.newMember = {
					...this.assignList.workOrderSignatureList[index]
				};
				this.$refs.addMemberPopup.open();
				this.tableKey++; // 强制刷新表格
			}, // 添加/修改成员后调用
			updateRowspan() {
				let currentGroup = ''
				let spanCount = 0

				this.assignList.workOrderSignatureList.forEach((item, index) => {
					if (item.group !== currentGroup) {
						currentGroup = item.group
						spanCount = 1
						// 向后查找相同group的项
						for (let i = index + 1; i < this.assignList.workOrderSignatureList.length; i++) {
							if (this.assignList.workOrderSignatureList[i].group === currentGroup) {
								spanCount++
							} else {
								break
							}
						}
						item.rowspan = spanCount
						item.showRow = true
					} else {
						item.rowspan = 0
						item.showRow = false
					}
				})

				this.tableKey++ // 强制刷新表格
			},
			// 获取食品生产工单详情
			async getfoodProductionInfo(orderId) {
				const id = {
					workOrderId: orderId
				}
				const res = await foodProductionInfo(id);
				if (res.code === 0) {
					this.assignList = res.data;
					this.dataChange = [
						new Date(this.assignList.checkStartTime).getTime(),
						new Date(this.assignList.checkEndTime).getTime()
					];
					
					this.assignList.workOrderSignatureList = this.assignList.workOrderSignatureList.map(item => ({
						...item,
						group: "核查组",
						
					}));
					   // 建议补充调用（若表格需要动态合并单元格）
					        this.updateRowspan(); 
					console.log(this.assignList.workOrderSignatureList )
				}
			},

			// 提交方法
			submitForm(status) {
				console.log(this.assignList)

				if (this.editStatus == 'FALSE') {
					uni.showToast({
						title: '当前处于查看状态',
						icon: 'none'
					});
				}
				if (this.editStatus === 'EDIT') {
					this.UPDATE(status);
				}

				if (this.editStatus === 'ADD') {
					this.ADD(status);
				}



			},
			//添加
			async ADD(status) {
				this.assignList.auditStatus = status;
				console.log(this.assignList)

				const res = await foodProductionAdd(this.assignList);
				if (res.code === 0) {
					// 显示成功提示 
					uni.showToast({
						title: '提交成功',
						icon: 'success',
						duration: 1500
					});
			// 关闭当前页面，跳转到工单页
			this.$closeAndRedirect({
			  url: '/pages/work/history/index'
			});
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}

			},
			//修改
			async UPDATE(status) {
				this.assignList.auditStatus = status;
				console.log(this.assignList)

				const res = await foodProductionUpdate(this.assignList);
				if (res.code === 0) {
					// 显示成功提示
					uni.showToast({
						title: '提交成功',
						icon: 'success',
						duration: 1500
					});
			// 关闭当前页面，跳转到工单页
			this.$closeAndRedirect({
			  url: '/pages/work/history/index'
			});
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}

			},



			/**
			 * @param {Object} e
			 * 经办人
			 */
			signToUrl(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				// 1. 解析响应数据（假设 e.data 是 JSON 字符串）
				const response = JSON.parse(e.data)
				this.assignList.checkPersonnelSignOne = response.data;
			},
			/**
			 * @param {Object} e
			 * 监督人
			 */
			signToUrl2(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)
				console.log(response.data);
				this.assignList.centerPersonSign = response.data;

			},
			/**
			 * @param {Object} e
			 * 批准人
			 */
			signToUrl3(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)
				this.assignList.approverPersonSign = response.data;


			},
			goHome() {
				this.$tab.navigateBack();
			},
			// 显示弹窗
			showAddMemberDialog() {
				this.isAddingHuiYi = false
				this.editingIndex = -1
				this.newMember = {
					group: '核查组',
					signaturePosition: '成员',
					userName: '',
					signature: '',
					showRow: true,
					rowspan: 1,
					signType: 0
				}
				this.$refs.addMemberPopup.open()
			},

			// 关闭弹窗
			closeMemberPopup() {
				this.$refs.addMemberPopup.close()
			},

			// 提交表单
			async submitMemberForm() {
				try {
					const valid = await this.$refs.memberForm.validate()
					if (valid) {
						const memberData = {
							...this.newMember,
							signType: this.isAddingHuiYi ? 1 : 0
						}

						if (this.editingIndex === -1) {
							// 新增
							if (this.isAddingHuiYi) {
								this.assignList.workOrderSignatureHuiYiList.push(memberData)
							} else {
								this.assignList.workOrderSignatureList.push({
									...memberData,
									showRow: true,
									rowspan: 1,
									group: '核查组'
								})
								this.updateRowspan()
							}
						} else {
							// 修改
							if (this.isAddingHuiYi) {
								this.assignList.workOrderSignatureHuiYiList.splice(this.editingIndex, 1, memberData)
							} else {
								this.assignList.workOrderSignatureList.splice(this.editingIndex, 1, memberData)
								this.updateRowspan()
							}
						}

						this.closeMemberPopup()
						uni.showToast({
							title: '操作成功'
						})
					}
				} catch (e) {
					console.error('表单验证失败:', e)
				}
			},
			handleDateRangeChange(e) {
				// 类型验证（避免小程序端数据类型不一致）
				if (Array.isArray(e)) {
					this.assignList.checkStartTime = this.formatDate(e[0])
					this.assignList.checkEndTime = this.formatDate(e[1])
				} else if (e?.detail?.value) { // 兼容微信小程序事件对象
					const [start, end] = e.detail.value
					this.assignList.checkStartTime = this.formatDate(start)
					this.assignList.checkEndTime = this.formatDate(end)
				}

				console.log('起始时间:', this.assignList.checkStartTime)
				console.log('结束时间:', this.assignList.checkEndTime)
			},
			formatDate(timestamp) {
				// 时间戳转日期字符串（示例格式：2025-03-25）
				return new Date(timestamp).toISOString().split('T')[0]
			},
			//获取字典值
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)

					// 增加响应状态判断
					if (res.code === 0) {

						switch (type) {
							case 'check_staff_form_wenan':
								this.remarkContent = res.data[0].remark
								break;
							case '2017':

							case 'bid_type':
								this.valueOptions = res.data.map(item => ({
									text: item.label,
									value: String(item.value) // 确保字典值转为字符串
								}));
								break;
							case 'mode_of_operation':
								this.modeOptions = res.data.map(item => ({
									text: item.label,
									value: String(item.value) // 确保字典值转为字符串
								}));


								break;

							default:
								return;
						}
					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}

				} catch (error) {
					uni.showToast({
						title: error.message || '获取分类失败',
						icon: 'none',
						duration: 2000
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		background-color: #e9f1fe;
		padding: 20px;
	}

	.cardView {
		font-size: 15px;
		margin-bottom: 10px;
		padding: 15px;
		background: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
	}

	/* 虚线容器 */
	.dashed-box {
		width: 100%;
		margin: 24rpx auto;
		padding: 12rpx;
		border: 2rpx dashed #333;
		border-radius: 10rpx;
		background: #fff;
		margin-bottom: 40px;
		position: relative;



		.custom-title {
			display: flex;
			margin-top: 10px;
			justify-content: center;
			align-items: center;
			margin-bottom: 10px;
			/* 保持原有下边距 */

		}

		.custom-text {

			color: black;
			font-size: 16px;
			font-weight: bold;
			text-align: right;
			margin-right: 20px;
		}


		.custom-dateText {
			display: flex;
			margin: 20px;
			justify-content: flex-end;
			/* 子元素居左 */
		}

		.custom-text-bottom {
			border-bottom: 1px solid #000;
			padding-bottom: 2px;
			padding-left: 10px;
			color: #0055ff;
			font-size: 16px;

			font-weight: bold;
			padding-right: 10px;
			margin-left: 4px;
			margin-right: 4px;
		}

	}

	.full-width-textarea {
		width: 100%;
		background-color: #e9f1fe;
		height: 200rpx;
		padding: 20rpx;
		box-sizing: border-box;
		border: 1rpx solid #e5e5e5;
		border-radius: 8rpx;
		font-size: 19rpx;
		line-height: 1.6;
	}

	.button-container {
		display: flex;
		background-color: #ffffff;
		width: 100%;
		padding: 10px;
		flex-direction: column;
		/* 垂直排列 */

		.button-save {
			margin-bottom: 10px;
		}

		.button-child {
			display: flex;
			flex-direction: row;
			/* 垂直排列 */

		}
	}

	/* 表格容器 */
	.table-container {
		max-height: 60vh;

		.term-table {
			font-size: 28rpx;

			.title-cell {
				font-weight: bold;
				color: #2d8cf0;
			}

			.content-cell {
				height: 180rpx;

				scroll-view {
					height: 100%;
					line-height: 1.6;
				}
			}
		}
	}


	/* 虚线容器 */
	.dashed {

		border: 2rpx dashed #0055ff;
		border-radius: 6rpx;
		background: #e5ecff;
		padding-top: 20px;
		padding-bottom: 20px;
		/* 设置为flex布局 */
		display: flex;
		/* 水平居中 */
		justify-content: center;
		margin-top: 30px;
		margin-bottom: 30px;
		/* 垂直居中 */
		align-items: center;
	}

	.remarkContent {
		padding: 10px;
		font-size: 13px;
	}

	.member-form-popup {
		background: #fff;
		padding: 30rpx;
		border-radius: 16rpx;
		width: 80vw;
	}

	.form-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 40rpx;

		.form-btn {
			flex: 0 48%;
			height: 60rpx;
			line-height: 60rpx;

			&.cancel {
				background: #f0f0f0;
				color: #666;
			}

			&.submit {
				background: #007AFF;
				color: white;
			}
		}
	}

	/* 调整表单项样式 */
	::v-deep .uni-forms-item__label {
		font-weight: bold;
		color: #333;
	}

	::v-deep .uni-easyinput__content {
		border-radius: 8rpx;
	}

	.centered-input {
		width: 100%;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		/* 保持与高度一致 */
		font-size: 16rpx;
		border-radius: 12rpx;
	}
</style>